/*
 * OREKIT-X
 * Copyright 2002-2008 CS Communication & Systemes
 * 
 * Parts of this software package have been licensed to CS
 * Communication & Systemes (CS) under one or more contributor license
 * agreements.  See the NOTICE file distributed with this work for
 * additional information.
 *  
 * This is an experimental copy of OREKIT from www.orekit.org.
 * Please use the original OREKIT from orekit.org for normal work
 * unrelated to this research project.
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); you
 * may not use this file except in compliance with the License.  You
 * may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
 * implied.  See the License for the specific language governing
 * permissions and limitations under the License.
 */
package ore.forces.gravity.potential;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.text.ParseException;
import java.util.Arrays;

import ore.errors.OrekitException;

/**
 * Reader for the SHM gravity potential format used by {@link PotentialReaderFactory}.
 *
 * This format was used to describe the gravity field of EIGEN models
 * published by the GFZ Potsdam up to 2003. It was then replaced by
 * {@link ICGEMFormatReader ICGEM format}. The SHM format is described
 * in <a href="http://www.gfz-potsdam.de/grace/results/"> Potsdam
 * university website</a>.
 *
 * @see PotentialReaderFactory
 * 
 * @author Fabien Maussion
 */
public class SHMFormatReader
    extends PotentialCoefficientsReader
{


    public SHMFormatReader(final String supportedNames) {
        super(supportedNames);
    }


    public void loadData(final InputStream input, final String name)
        throws IOException, ParseException, OrekitException
    {
        BufferedReader r = new BufferedReader(new InputStreamReader(input));
        boolean okEarth  = false;
        boolean okSHM    = false;
        boolean okCoeffs = false;
        String line = r.readLine();
        if ("FIRST ".equals(line.substring(0, 6)) &&
            "SHM    ".equals(line.substring(49, 56))) {
            for (line = r.readLine(); line != null; line = r.readLine()) {
                if (line.length() >= 6) {
                    final String[] tab = line.split("\\s+");
                    switch (Format.For(tab[0])){
                        /*
                         * Read the earth values
                         */
                    case EARTH:
                        this.mu = Double.parseDouble(tab[1].replace('D', 'E'));
                        this.ae = Double.parseDouble(tab[2].replace('D', 'E'));
                        okEarth = true;
                        break;
                        /*
                         * Initialize the arrays
                         */
                    case SHM:{
                        final int i = Integer.parseInt(tab[1]);
                        this.normalizedC = new double[i + 1][];
                        this.normalizedS = new double[i + 1][];
                        for (int k = 0; k < this.normalizedC.length; k++) {
                            this.normalizedC[k] = new double[k + 1];
                            this.normalizedS[k] = new double[k + 1];
                            Arrays.fill(normalizedC[k], Double.NaN);
                            Arrays.fill(normalizedS[k], Double.NaN);
                        }
                        okSHM = true;
                        break;
                    }
                        /*
                         * Fill the arrays
                         */
                    case GRCOEF:{
                        int i = Integer.parseInt(tab[1]);
                        int j = Integer.parseInt(tab[2]);
                        this.normalizedC[i][j] = Double.parseDouble(tab[3].replace('D', 'E'));
                        this.normalizedS[i][j] = Double.parseDouble(tab[4].replace('D', 'E'));
                        okCoeffs = true;
                        break;
                    }
                    case GRCOF2:{
                        int i = Integer.parseInt(tab[1]);
                        int j = Integer.parseInt(tab[2]);
                        this.normalizedC[i][j] = Double.parseDouble(tab[3].replace('D', 'E'));
                        this.normalizedS[i][j] = Double.parseDouble(tab[4].replace('D', 'E'));
                        okCoeffs = true;
                        break;
                    }
                    }
                }
            }

            for (int k = 0; okCoeffs && k < normalizedC.length; k++) {
                final double[] cK = normalizedC[k];
                final double[] sK = normalizedS[k];
                for (int i = 0; okCoeffs && i < cK.length; ++i) {
                    if (Double.isNaN(cK[i])) {
                        okCoeffs = false;
                    }
                }
                for (int i = 0; okCoeffs && i < sK.length; ++i) {
                    if (Double.isNaN(sK[i])) {
                        okCoeffs = false;
                    }
                }
            }

            if (!(okEarth && okSHM && okCoeffs)) {
                throw new OrekitException("the reader is not adapted to the format ({0})",
                                          name);
            }
            else
                this.readCompleted = true;
        }
    }

    private enum Format {
        EARTH, SHM, GRCOEF, GRCOF2, NIL;

        static Format For(String tab){
            try {
                return valueOf(tab);
            }
            catch (RuntimeException exc){
                return NIL;
            }
        }
    }
}
